package com.efounder.fragment;

import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;

import com.core.xml.StubObject;
import com.efounder.frame.baseui.BaseFragment;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.ospmobilelib.R;
import com.efounder.util.CheckNetWork;
import com.efounder.util.LoadingDataUtilBlack;
import com.efounder.util.StorageUtil;
import com.pansoft.espcomp.PansoftWebView;
import com.pansoft.espcomp.PansoftWebView.JsToAndroidInterface;
import com.pansoft.pullrefresh.ui.PullToRefreshBase;
import com.pansoft.pullrefresh.ui.PullToRefreshBase.OnRefreshListener;
import com.pansoft.pullrefresh.ui.PullToRefreshNormalWebView;

import java.io.FileInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Hashtable;
import java.util.Locale;

import static com.efounder.frame.utils.Constants.KEY_SETTING_APPID;
import static com.efounder.frame.utils.Constants.KEY_SETTING_DEFAULT_SERVER_ADDRESS;
import static com.efounder.frame.utils.Constants.KEY_SETTING_DEFAULT_SERVER_HTTP_TYPE;
import static com.efounder.frame.utils.Constants.KEY_SETTING_DEFAULT_SERVER_PATH;
import static com.efounder.frame.utils.Constants.KEY_SETTING_DEFAULT_SERVER_PORT;

public class WebviewFragment extends BaseFragment {
	private static final String TAG = "SimpleWebFragmentNoRefresh";
	private StubObject mMenuItem;
	private FrameLayout fl;
	private String forms, titleStr;
	private PansoftWebView webView;
	private StorageUtil storageUtilforwebview;
	private PullToRefreshNormalWebView mPullWebView;
	private SimpleDateFormat mDateFormat = new SimpleDateFormat("MM-dd HH:mm",
			Locale.getDefault());
	private String URLofThisPage;

	// 无网络环境加载错误页面
	private String errorURL = "file:///android_asset/error.html";
	// 服务器错误加载错误页面
	private String serverErrorURL = "file:///android_asset/servererror.html";
	static String sdDir = null;
	static {

		boolean sdCardExist = Environment.getExternalStorageState().equals(
				android.os.Environment.MEDIA_MOUNTED); // 判断sd卡是否存在
		if (sdCardExist) {
			sdDir = Environment.getExternalStorageDirectory().toString();// 获取跟目录
		} else {
			sdDir = Environment.getRootDirectory().toString();
		}

	}
	// public static final String EXTERNAL_ROOT =
	// Environment.getExternalStorageDirectory().toString();
	public static final String EXTERNAL_ROOT = sdDir;

	/**
	 * 应用程序根目录
	 */
	public static final String APP_ROOT = EXTERNAL_ROOT + EnvironmentVariable.getProperty(KEY_SETTING_APPID);
	// private static final String TAG = "Mystaticwebview";

	private String ServerURL;
	
	private String ifNeedRedis = "0";

	public WebviewFragment() {
		super();
	}

	public WebviewFragment(StubObject menuItem, String title) {
		this.mMenuItem = menuItem;
		this.titleStr = title;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View rootView = inflater.inflate(R.layout.webviewforhtml, container,
				false);

		mPullWebView = (PullToRefreshNormalWebView) rootView
				.findViewById(R.id.mywebview);

		if (null != savedInstanceState) {
			mMenuItem = (StubObject) savedInstanceState
					.getSerializable("databack");
			titleStr = (String) savedInstanceState.getSerializable("title");
		}

		webView = mPullWebView.getRefreshableView();
		OnRefreshListener<PansoftWebView> listner = new OnRefreshListener<PansoftWebView>() {
			@Override
			public void onPullDownToRefresh(
					PullToRefreshBase<PansoftWebView> refreshView) {
				// TODO Auto-generated method stub
				ifNeedRedis = "1";
				webView.loadUrl(URLofThisPage+"?redisrefresh=1");
			}

			public void onPullUpToRefresh(
					PullToRefreshBase<PansoftWebView> refreshView) {
				// TODO Auto-generated method stub

			}
		};
		mPullWebView.setOnRefreshListener(listner);

		webView.getSettings().setJavaScriptEnabled(true);
		/*
		 * webView.setWebChromeClient(new WebChromeClient() );
		 */
		webView.getSettings().setSupportZoom(true);
		webView.getSettings().setBuiltInZoomControls(true);
		webView.getSettings().setDisplayZoomControls(false);// 设定缩放控件隐藏
		webView.getSettings().setTextSize(
				webView.getSettings().getTextSize().NORMAL);
		webView.setVerticalFadingEdgeEnabled(false);

		// webView.setWebViewClient(new WebViewClient() {});
		// webView.getSettings().setLoadWithOverviewMode(true); // 缩放至屏幕的大小
		webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
		/*
		 * webView.setWebChromeClient(new WebChromeClient(){
		 * 
		 * @Override public boolean onJsAlert(WebView view, String url, String
		 * message, JsResult result) { // TODO Auto-generated method stub return
		 * super.onJsAlert(view, url, message, result); } } );
		 */
		webView.getSettings().setSupportZoom(true);
		webView.getSettings().setBuiltInZoomControls(true);
		webView.getSettings().setDisplayZoomControls(false);// 设定缩放控件隐藏
		webView.getSettings().setTextSize(
				webView.getSettings().getTextSize().NORMAL);
		webView.setVerticalFadingEdgeEnabled(false);
		webView.setWebViewClient(new WebViewClient() {

			@Override
			public void onLoadResource(WebView view, String url) {

				// System.out.println("url===="+url);
				Log.i(TAG, "onLoadResource url=" + url);

				super.onLoadResource(view, url);
			}

			@Override
			public void onPageFinished(WebView view, String url) {
				super.onPageFinished(view, url);
				Log.i(TAG, titleStr + "---------------onPageFinished");
				setLastUpdateTime();
				mPullWebView.onPullDownRefreshComplete();
				LoadingDataUtilBlack.dismiss();
			}

			@Override
			public void onReceivedError(WebView view, int errorCode,
					String description, String failingUrl) {
				super.onReceivedError(view, errorCode, description, failingUrl);
				// TODO Auto-generated method stub
				Boolean netWork = CheckNetWork
						.isNetworkConnected(getActivity());
				if (netWork) {
					view.loadUrl(serverErrorURL);
				} else {
					view.loadUrl(errorURL);
					
				}
			}

			@Override
			public WebResourceResponse shouldInterceptRequest(WebView view,
					String url) {

				System.out.println("webviewfragement======================="
						+ url);
				WebResourceResponse response = null;
				if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
					if ((!url.contains(ServerURL) && !url
							.contains("favicon.ico"))
							|| url.contains("CtrlService")
							|| url.contains(".html"))
						return null;

					if (url.contains("favicon.ico")) {
						url = APP_ROOT + "/res/unzip_res/HTML5/"
								+ "favicon.ico";
						System.out.println("url for favicon.icon=======" + url);
					} else {
						/*
						 * if(url.contains("jsforandroid/"))
						 * url=url.replace("jsforandroid/", "");
						 */
						String content = url.substring(url.indexOf(ServerURL)
								+ (ServerURL).length(), url.length());

						url = APP_ROOT + "/res/unzip_res" + content;
						if (url.contains("bar")) {
							System.out.println(url);
						}
					}
					try {
						FileInputStream localCopy = new FileInputStream(url);

						response = new WebResourceResponse(null, "UTF-8",
								localCopy);
					} catch (IOException e) {
						e.printStackTrace();
					} finally {
						System.out.println(url + ".........over");
					}

				}

				return response;
			}
		});

		webView.setJsToAndroidInterface(new JsToAndroidInterface() {

			public void jsToAndroid(String xx) {
				// TODO Auto-generated method stub
				if (xx.equals("OpenDialogForJH")) {
					mPullWebView.setPullRefreshEnabled(false);
				} else if (xx.equals("CloseDialogForJH")) {
					mPullWebView.setPullRefreshEnabled(true);
				}
			}

			public void jsToAndroid() {
				// TODO Auto-generated method stub

			}
			public String getIfNeedRedis(){
				return ifNeedRedis;
				
			}
		});
		/*
		 * webView.setWebViewClient(new WebViewClient() { public boolean
		 * shouldOverrideUrlLoading(WebView view, String url) { //
		 * 重写此方法表明点击网页里面的链接还是在当前的webview里跳转，不跳到浏览器那边 view.loadUrl(url); return
		 * true; } });
		 */

		storageUtilforwebview = new StorageUtil(
				WebviewFragment.this.getActivity(), "storage");
//		String address = storageUtilforwebview.getString("address", "");
//		String path = storageUtilforwebview.getString("path", "");
//		String port = storageUtilforwebview.getString("port", "8080");
//		boolean isSafe = storageUtilforwebview.getBoolean("isSafe", true);
//		String protocol = null;
//		if (isSafe) {
//			protocol = "https";
//		} else {
//			protocol = "http";
//		}
		String address = EnvironmentVariable.getProperty(KEY_SETTING_DEFAULT_SERVER_ADDRESS);
		String path = EnvironmentVariable.getProperty(KEY_SETTING_DEFAULT_SERVER_PATH);
		String port = EnvironmentVariable.getProperty(KEY_SETTING_DEFAULT_SERVER_PORT);

		String protocol =EnvironmentVariable.getProperty(KEY_SETTING_DEFAULT_SERVER_HTTP_TYPE);
		ServerURL = protocol + "://" + address + "/" + path;

		Hashtable menuTable = mMenuItem.getStubTable();
		forms = (String) menuTable.get("forms");
		URLofThisPage = ServerURL + "/AndroidForm/" + forms + ".html";

		// Window级别 开启硬件加速 注意：现阶段你不能在Window级别对它禁用硬件加速。
		getActivity().getWindow().setFlags(
				WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED,
				WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED);

		super.onCreateView(inflater, container, savedInstanceState);
		return rootView;

	}

	@Override
	public void onVisible() {
		LoadingDataUtilBlack.show(WebviewFragment.this.getActivity());
		webView.loadUrl(URLofThisPage);
		super.onVisible();
	}

	@Override
	public void onInvisible() {

		super.onInvisible();
	}

	private void setLastUpdateTime() {
		String text = formatDateTime(System.currentTimeMillis());
		mPullWebView.setLastUpdatedLabel(text);
	}

	private String formatDateTime(long time) {
		if (0 == time) {
			return "";
		}

		return mDateFormat.format(new Date(time));
	}

	@Override
	public void onSaveInstanceState(Bundle outState) {
		// TODO Auto-generated method stub
		super.onSaveInstanceState(outState);
		outState.putSerializable("databack", mMenuItem);
		outState.putSerializable("title", titleStr);
	}

}
